import Vue from 'vue'
import co from 'co'
// import CommonService from './CommonService'
import * as Util from '../../components/Util'

// 判断是否有卡插入
let hasCardGen = function * () {
  return yield Vue.resetpost('http://127.0.0.1:8003/HasCard', {}, {resolveMsg: null, rejectMsg: null})
}
// 读卡
let readCard = function * () {
  return yield Vue.resetpost('http://127.0.0.1:8003/ReadCard', {data: {}}, {resolveMsg: null, rejectMsg: null})
}
// 新开户
let initCardGen = function * (model, row, allot) {
  let result = null
  let allotback
  try {
    // 写卡之前是否需要读一次卡或和卡服务及读卡器交互一次，以确保卡与卡服务相关系统正常，提高写卡成功率
    // let logicRes = yield Vue.$post(logicPath, {data: logicParams}, {resolveMsg: null, rejectMsg: '开户逻辑错误'})

    // 根据预购气量计算应交金额
    // let cal = yield CommonService.gasCalculate(data, data.f_payment)

    // 卡操作顺序：1.存库，2.后写卡，3.判断写卡是否成功，成功，修改售气标识，失败，业务回滚
    let cardState = yield co(hasCardGen())
    if (JSON.parse(cardState.data).state === 1) {
      // 存库
      result = yield co(saleGasGen(model, row))
      if (allot) {
        allotback = yield Vue.resetpost('rs/logic/saveAllotData', {data: allot}, {resolveMsg: null, rejectMsg: '更新发卡信息失败'})
      }
      // 由于数据太长，将f_user_id 更改为字符串
      // row.f_user_id = row.f_user_id.toString()
      Vue.console.info(result, 'CardService')
      // 获取气价和售气情况参数
      let cardParams = yield co(getParamGen(result.data.cardnumber, row.f_alias))
      console.log('获取写卡参数，，，，123', cardParams)
      // 写卡
      let params = {
        factory: row.f_alias,
        kmm: '000000',                                       // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
        kzt: '0',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
        kh: result.data.cardnumber,                          // 卡号
        yhh: row.f_meterid,                                  // 用户号，档案中自己输
        ql: model.f_pregas,                                  // 预购气量
        csql: '0',                                           // 上次购气量，新开户为0
        ccsql: '0',                                          // 上上次购气量，新开户为0
        cs: '1',                                             // 求购气次数，先开户为1
        ljgql: model.f_pregas,                               // 当前累计购气量
        bkcs: '0',                                           // 新开户卡，为0
        ljyql: '0',                                          // 累积用气量，有些表要累加原来用气量,新开户卡，为0
        bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
        czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
        tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
        cssqrq: '0',                                          // 上次售气日期，格式为YYYYMMDD
        meterid: row.f_meternumber,                          // 表号
        money: model.f_preamount                            // 购气金额
      }
      params = Object.assign({}, Vue.CommonService.writeCardParams(cardParams), params)
      if (row.f_alias === 'HaiLiJE' || row.f_alias === 'HaiLiQL' || row.f_alias === 'CangNanTY') {
        params.klx = yield co(getmodelbrandGen(row))
        params.klx = params.klx.data[0].f_coding
      }
      let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '开户卡服务错误'}))

      // 卡服务写卡异常，业务逻辑回滚
      if (!cardParams || !result || cardRes.data.Err || cardRes.data.Exception) {
        row.version = row.version + 1
        row.userinfo_version = row.userinfo_version + 1
        // 由于数据太长，将f_user_id 更改为字符串
        row.f_user_id = row.f_user_id + ''
        Vue.console.info(result.data.id, 'CardService')
        yield Vue.resetpost('rs/logic/salecardrollback', {data: {id: result.data.id, row: row}}, {resolveMsg: '开户失败', rejectMsg: '开户失败'})
        // 更新卡状态为作废
        if (allot) {
          yield Vue.resetpost('rs/logic/allotDataRollback', {data: allotback.data}, {resolveMsg: null, rejectMsg: '更新发卡信息失败'})
        }
      } else {
        // 如果成功修改标识(更新状态为有效)，将返回的卡密码写回数据库
        row.version = row.version + 1
        let data = {
          userfiles: {
            f_user_id: row.f_user_id + '',
            f_times: 1,
            version: row.version,
            f_card_id: result.data.cardnumber,
            f_card_password: cardRes.data.Kmm
          },
          record: {
            id: result.data.id,
            f_state: '有效'
          }
        }
        yield Vue.resetpost('rs/logic/updatemark', {data: data}, {resolveMsg: '开户成功', rejectMsg: '开户修改状态失败'})
      }
    } else {
      Vue.showAlert('请检查卡是否插好！！', 'danger', 3000)
    }
  } catch (error) {
    // Vue.console.error('出错', error)
    let msg = ''
    if (error.status === 612) {
      msg = '请检查读卡器时候连接,或者卡服务是否启动！！'
    } else {
      msg = '开户失败！！'
      row.version = row.version + 1
      row.userinfo_version = row.userinfo_version + 1
      // 由于数据太长，将f_user_id 更改为字符串
      row.f_user_id = row.f_user_id + ''
      Vue.console.info(result.data.id, 'CardService')
      yield Vue.resetpost('rs/logic/salecardrollback', {data: {id: result.data.id, row: row}}, {resolveMsg: null, rejectMsg: null})
      // 更新卡状态为作废
      if (allot) {
        yield Vue.resetpost('rs/logic/allotDataRollback', {data: allotback.data}, {resolveMsg: null, rejectMsg: '更新发卡信息失败'})
      }
    }
    Vue.showAlert(msg, 'danger', 0)
  }
}

// 补卡管理
let replaceCardGen = function * (model, row, allot) {
  let result = null
  let allotback
  try {
    // 判断是否有卡
    let cardState = yield co(hasCardGen())
    if (JSON.parse(cardState.data).state === 1) {
      console.log('补卡管理..model', model)
      console.log('补卡管理..row', row)
      // 存库
      result = yield co(reissueCardGen(model, row))
      if (allot) {
        allotback = yield Vue.resetpost('rs/logic/saveAllotData', {data: allot}, {resolveMsg: null, rejectMsg: '更新发卡信息失败'})
      }
      // 获取气价和售气情况参数
      let cardParams = yield co(getParamGen(row.f_card_id, row.f_alias))

      // 写卡
      let params = {
        factory: row.f_alias,
        kh: row.f_card_id,                                   // 卡号
        kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
        bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
        czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
        tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
        kzt: '1',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
        bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
        cs: row.f_times,                                        // 求购气次数，先开户为1
        meterid: row.f_meterid,                  // 表号
        money: 0                           // 购气金额
      }
      params = Object.assign({}, Vue.CommonService.writeCardParams(cardParams), params)
      if (row.f_alias === 'HaiLiJE' || row.f_alias === 'HaiLiQL' || row.f_alias === 'CangNanTY') {
        params.klx = yield co(getmodelbrandGen(row))
        params.klx = params.klx.data[0].f_coding
      }
      console.log('补卡是写的次数。。。。', params)

      let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '补卡卡服务错误'}))
      // 卡服务写卡异常，业务逻辑回滚
      if (!cardParams || !result || cardRes.data.Err || cardRes.data.Exception) {
        yield Vue.resetpost('rs/logic/repairCardRoolBack', {data: {id: result.data.id}}, {resolveMsg: '补卡失败', rejectMsg: '补卡失败'})
        // 更新卡状态为作废
        if (allot) {
          yield Vue.resetpost('rs/logic/allotDataRollback', {data: allotback.data}, {resolveMsg: null, rejectMsg: null})
        }
      } else {
        // 如果成功修改标识(更新状态为有效)
        let data = {
          userfiles: {
            f_user_id: row.f_user_id + '',
            f_times: row.f_times,
            version: row.version
          },
          record: {
            id: result.data.id,
            f_state: '有效'
          }
        }
        yield Vue.resetpost('rs/logic/updatemark', {data: data}, {resolveMsg: '补卡成功', rejectMsg: '补卡修改状态失败'})
      }
    } else {
      Vue.showAlert('请检查卡是否插好！！', 'danger', 3000)
    }
  } catch (error) {
    let msg = ''
    if (error.status === 612) {
      msg = '请检查读卡器时候连接,或者卡服务是否启动！！'
    } else {
      msg = '补卡失败！！'
      yield Vue.resetpost('rs/logic/repairCardRoolBack', {data: {id: result.data.id}}, {resolveMsg: '补卡失败', rejectMsg: '补卡失败'})
    }
    // 更新卡状态为作废
    if (allot) {
      yield Vue.resetpost('rs/logic/allotDataRollback', {data: allotback.data}, {resolveMsg: null, rejectMsg: null})
    }
    Vue.showAlert(msg, 'danger', 0)
  }
}

// 卡表收费
let sellGasGen = function * (model, row) {
  let result
  try {
    let cardState = yield co(hasCardGen())
    if (JSON.parse(cardState.data).state === 1) {
      // 存库
      result = yield co(cardChargeGen(model, row))

      // 获取气价和售气情况参数
      let cardParams = yield co(getParamGen(row.f_card_id, row.f_alias))
      console.log('写卡次数和获取的写卡参数...', row.cardInfo.Times, cardParams)
      // 写卡
      let params = {
        factory: row.f_alias,                                // 气表厂家
        kh: row.f_card_id,                                   // 卡号
        // yhh: row.f_meterid,                               // 用户号，档案中自己输
        kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
        bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
        czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
        tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
        bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
        ql: model.f_pregas,                                  // 预购气量
        cs: row.cardInfo.Times + 1,                         // 求购气次数，先开户为1
        money: model.f_preamount                            // 购气金额
      }
      params = Object.assign({}, Vue.CommonService.writeCardParams(cardParams), params)
      if (row.f_alias === 'HaiLiJE' || row.f_alias === 'HaiLiQL' || row.f_alias === 'CangNanTY') {
        params.klx = yield co(getmodelbrandGen(row))
        params.klx = params.klx.data[0].f_coding
      }

      let params2 = {
        factory: row.f_alias,
        kh: row.f_card_id,                                   // 卡号
        kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
        bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
        czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
        tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
        kzt: '1',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
        bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
        ql: model.f_pregas,                                  // 预购气量
        cs: row.cardInfo.Times + 1,                                       // 求购气次数，先开户为1
        sxrq: model.f_startdate,                             // 生效日期，价格管理中取
        meterid: row.f_meterid,                  // 表号
        money: model.f_preamount                            // 购气金额
      }

      params2 = Object.assign({}, Vue.CommonService.writeCardParams(cardParams), params2)
      if (row.f_alias === 'HaiLiJE' || row.f_alias === 'HaiLiQL' || row.f_alias === 'CangNanTY') {
        params2.klx = yield co(getmodelbrandGen(row))
        params2.klx = params2.klx.data[0].f_coding
      }

      let params3 = {
        factory: row.f_alias,
        kh: row.f_card_id,                                   // 卡号
        kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
        bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
        czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
        tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
        kzt: '0',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
        bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
        ql: model.f_pregas,                                  // 预购气量
        cs: 1,                                        // 求购气次数，先开户为1
        sxrq: model.f_startdate,                             // 生效日期，价格管理中取
        meterid: row.f_meterid,                  // 表号
        money: model.f_preamount                            // 购气金额
      }
      params3 = Object.assign({}, Vue.CommonService.writeCardParams(cardParams), params3)
      if (row.f_alias === 'HaiLiJE' || row.f_alias === 'HaiLiQL' || row.f_alias === 'CangNanTY') {
        params3.klx = yield co(getmodelbrandGen(row))
        params3.klx = params3.klx.data[0].f_coding
      }
      let cardRes
      if (row.f_states === '补卡') {
        console.log('我走的是写新卡补卡')
        cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params2, {resolveMsg: null, rejectMsg: '卡表收费失败'}))
      } else if (row.f_states === '换表') {
        console.log('我走的是写新卡换表')
        cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params3, {resolveMsg: null, rejectMsg: '卡表收费失败'}))
      } else {
        console.log('我走的是正常的收费', params)
        cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteGasCard', params, {resolveMsg: null, rejectMsg: '卡表收费失败'}))
      }
      // 卡服务写卡异常，业务逻辑回滚
      if (!cardParams || !result || cardRes.data.Err || cardRes.data.Exception) {
        Vue.showAlert('卡表收费失败，请核实卡上气量，和收费记录，确认是否再次购气，或换卡购气。', 'danger', 0)
        let data = {
          id: result.data.id,
          userinfo: {
            f_userinfo_id: row.f_userinfo_id,
            version: row.userinfo_version + 1,
            f_balance: row.f_balance,
            userfiles: {
              f_user_id: model.f_user_id,
              f_meter_base: row.f_meter_base,
              f_total_fee: row.f_total_fee,
              version: row.version + 1
            }
          }
        }
        yield Vue.resetpost('rs/logic/cardChargeRollback', {data: data}, {resolveMsg: null, rejectMsg: null})
      } else {
        // 如果成功修改标识(更新状态为有效)
        let data = {
          id: result.data.id,
          f_state: '有效'
        }
        yield Vue.resetpost('rs/entity/t_record', data, {resolveMsg: '售气成功', rejectMsg: '卡表收费修改状态失败'})
      }
    } else {
      Vue.showAlert('请检查卡是否插好！！', 'danger', 3000)
    }
  } catch (error) {
    let msg = ''
    if (error.status === 612) {
      msg = '请检查读卡器时候连接,或者卡服务是否启动'
    } else {
      msg = '收费失败'
      let data = {
        id: result.data.id,
        userinfo: {
          f_userinfo_id: row.f_userinfo_id,
          version: row.userinfo_version + 1,
          f_balance: row.f_balance
        }
      }
      yield Vue.resetpost('rs/logic/cardChargeRollback', {data: data}, {resolveMsg: '卡表收费失败', rejectMsg: '卡表收费失败'})
    }
    Vue.showAlert(msg, 'danger', 0)
  }
}
// let getstairGen = function * (row) {
//   return co(Vue.resetpost('rs/sql/getStairs', {data: {id: row.f_price_id
//   }
//   }, {resolveMsg: null, rejectMsg: null}))
// }
let getmodelbrandGen = function * (row) {
  return co(Vue.resetpost('rs/sql/singleTable_OrderBy', {data: {
    items: 'f_coding', tablename: 't_gasmodel', condition: `id = ${row.f_gasmodel_id}`, orderitem: 'id'
  }
  }, {resolveMsg: null, rejectMsg: null}))
}
let reissueCardGen = function * (model, row, allot) {
  if (model.f_fillcard_type === 'IC卡信息错乱') {
    model.f_reason = 'IC卡信息错乱'
  } else if (model.f_fillcard_type === 'IC卡丢失') {
    model.f_reason = 'IC卡丢失'
  } else if (model.f_fillcard_type === 'IC卡坏') {
    model.f_reason = 'IC卡坏'
  }
  if (model.f_cardfees === '') {
    model.f_cardfees = 0
  }
  let data = {
    f_user_id: row.f_user_id,
    f_fillcard_type: model.f_fillcard_type,
    f_fillcard_state: '有效',
    f_card_id: row.f_card_id,
    f_cardfees: model.f_cardfees,
    f_reason: model.f_reason,
    record_userinfo: row.f_userinfo_id,
    f_userinfo_id: row.f_userinfo_id,
    f_user_name: row.f_user_name,
    f_operat_type: '补卡',
    f_describe: `${Util.f.name}对用户${row.f_user_name}进行补卡操作`,
    f_state: '未知',
    f_operator: Util.f.name,
    f_filiale: Util.f.f_fengongsi,
    f_outlets: Util.f.f_parentname
  }
  return Vue.resetpost('rs/entity/t_fillcard', data, {resolveMsg: null, rejectMsg: '补卡存库失败'})
}

let saleGasGen = function * (model, row) {
  let data = {
    f_tablebase: (row.f_meter_base - 0) + (model.f_pregas - 0),
    f_last_tablebase: row.f_meter_base,
    f_pregas: model.f_pregas,
    f_preamount: model.f_preamount,
    f_user_id: row.f_user_id + '',
    record_userinfo: row.f_userinfo_id + '',
    f_operat_type: '发卡售气',
    f_describe: `${Util.f.name}对用户${row.f_user_name}进行发卡售气操作`,
    f_state: '未知',
    f_operator: Util.f.name,
    f_delaypay: 0,
    f_charge_type: '发卡售气',
    chargeprice: model.chargeprice,
    f_filiale: Util.f.f_fengongsi,
    f_outlets: Util.f.f_parentname,
    userinfo: {
      f_userinfo_id: row.f_userinfo_id + '',
      version: row.userinfo_version,
      f_balance: model.f_curbalance,
      userfiles: {
        f_user_id: model.f_user_id + '',
        f_whether_hairpin: '已发',
        f_meter_base: (row.f_meter_base - 0) + (model.f_pregas - 0),
        f_total_fee: (row.f_total_fee - 0) + (model.f_preamount - 0),
        version: row.version
      }
    }
  }

  Object.assign(data, data, Vue.CommonService.buildSellinggas(model, row))

  return Vue.resetpost('rs/logic/salecard', {data: data}, {resolveMsg: null, rejectMsg: '发卡售气存库失败'})
}

let cardChargeGen = function * (model, row) {
  let data = {
    f_tablebase: (row.f_meter_base - 0) + (model.f_pregas - 0),
    f_last_tablebase: row.f_meter_base,
    f_pregas: model.f_pregas,
    f_preamount: model.f_preamount,
    record_userinfo: row.f_userinfo_id,
    f_user_id: row.f_user_id,
    f_card_id: row.f_card_id,
    f_operat_type: '卡表收费',
    f_describe: `${Util.f.name}对用户${row.f_user_name}进行卡表收费操作`,
    f_state: '未知',
    f_operator: Util.f.name,
    f_delaypay: 0,
    f_charge_type: '卡表收费',
    chargeprice: model.chargeprice,
    f_filiale: Util.f.f_fengongsi,
    f_outlets: Util.f.f_parentname,
    userinfo: {
      f_userinfo_id: row.f_userinfo_id,
      version: row.userinfo_version,
      f_balance: model.f_curbalance,
      userfiles: {
        f_user_id: model.f_user_id,
        f_meter_base: (row.f_meter_base - 0) + (model.f_pregas - 0),
        f_total_fee: (row.f_total_fee - 0) + (model.f_preamount - 0),
        version: row.version
      }
    }
  }
  data.userinfo.userfiles.f_times = row.cardInfo.Times + 1
  if (row.f_states === '正常') {
    data.userinfo.userfiles.f_meterid = row.cardInfo.Yhh
  }
  console.log('卡表收费，看看总累计购气金额，，', data)
  Object.assign(data, data, Vue.CommonService.buildSellinggas(model, row))
  return Vue.resetpost('rs/entity/t_sellinggas', data, {resolveMsg: null, rejectMsg: '卡表收费存库失败'})
}
let getParamGen = function * (cardid, alias) {
  let data = {
    f_card_id: cardid + '',
    f_alias: alias
  }
  return co(Vue.resetpost('rs/logic/stairCard', {data: data}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'}))
}
// 更新卡分配信息  现使用卡号
let updateCardAllotMsg = function * (allot) {
  allot.f_now_number = parseInt(allot.f_now_number) + 1
  return Vue.resetpost('rs/entity/f_cardallot', {data: allot}, {resolveMsg: null, rejectMsg: '更新卡号失败'})
}
let CardService = {
  install (Vue, options) {
    // 给vue增添对话框显示方法
    Vue.CardService = Vue.prototype.$CardService = CardService
  },
  // 判断是否插卡
  hasCard () {
    let has = hasCardGen()
    return co(has)
  },
  // 读卡
  readCard () {
    let read = readCard()
    return co(read)
  },
  // 开户发卡
  initCard (model, row, allot) {
    let init = initCardGen(model, row, allot ? this.getallotdata(allot, row, '发卡售气') : null)
    return co(init)
  },
  // 补卡存库
  reissueCard (model, row) {
    let reissue = reissueCardGen(model, row)
    return co(reissue)
  },
  // 补卡写卡
  replaceCard (model, row, allot) {
    let replace = replaceCardGen(model, row, allot ? this.getallotdata(allot, row, '补卡') : null)
    return co(replace)
  },
  // 售气存库
  salegas (model, row) {
    let salegas = saleGasGen(model, row)
    return co(salegas)
  },
  // 售气写卡
  sellgas (model, row) {
    let sellgas = sellGasGen(model, row)
    return co(sellgas)
  },
  // 卡表收费
  cardCharge (model, row) {
    let cardcharge = cardChargeGen(model, row)
    return co(cardcharge)
  },
  // // 新增一条卡详细信息
  getallotdata (allot, row, type) {
    // 更改卡分配 中卡号的值
    let allotdata = {
      newallot: {
        id: allot.id,
        f_now_number: parseInt(allot.f_now_number) + 1
      },
      // 新增一条卡详细信息
      allotdetail: {
        f_card_number: parseInt(allot.f_now_number) + 1,
        f_allot_id: allot.id,
        f_userinfo_id: row.f_userinfo_id,
        f_user_name: row.f_user_name,
        f_allot_name: allot.f_user,
        f_card_type: allot.f_card_type,
        f_card_state: '正常',
        f_operator: Util.f.name,
        f_operator_type: type,
        f_operate_date: Util.toStandardTimeString(),
        f_filiale: Util.f.f_fengongsi,
        f_outlets: Util.f.f_parentname
      }
    }
    return allotdata
  }
}

export default CardService
